//This file contains the authentication middleware.
import 'dart:io';

import 'package:simple_server/src/context.dart';
import 'package:simple_server/src/middleware/middleware.dart';

typedef CheckAuth<T extends Context> = Future<void> Function(
  String? token,
  T context,
  Next next,
);

class AuthMiddleware<T extends Context> extends Middleware<T> {
  final _pathCheckAuthMap = <String, CheckAuth<T>>{};

  void addCheckAuth(String path, CheckAuth<T> checkAuth) {
    _pathCheckAuthMap[path] = checkAuth;
  }

  @override
  Future<void> call(T context, Next next) async {
    final header = context.headers[HttpHeaders.authorizationHeader];
    final token = header?.firstOrNull?.split(' ').lastOrNull;
    if (token != null && token.isNotEmpty) context['token'] = token;
    final checkAuth = _pathCheckAuthMap[context.path];
    if (checkAuth == null) return await next();
    context.statusCode = HttpStatus.unauthorized;
    await checkAuth(token, context, next);
  }
}
